<template>
    <el-card class="!border-none" shadow="never">
        <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
            <el-form-item>
                <el-input
                    class="w-[300px]"
                    v-model="queryParams.real_name"
                    placeholder="教师名称"
                    clearable
                    @keyup.enter="resetPage"
                ></el-input>
            </el-form-item>

            <el-form-item>
                <el-cascader
                    v-model="queryParams.college"
                    class="w-[300px]"
                    @change="collegeChange"
                    :options="data"
                    placeholder="院系/班级"
                ></el-cascader>
            </el-form-item>

            <el-form-item>
                <el-date-picker
                    v-model="queryParams.value2"
                    start-placeholder="选择开始时间"
                    end-placeholder="选择结束时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    class="w-[300px]"
                    placeholder="以创建时间范围筛选"
                    @change="dateChange"
                ></el-date-picker>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="resetPage">
                    <div>
                        <!-- <span class="search_btn_icon"> </span> -->
                        查询
                    </div>
                </el-button>
                <el-button @click="resetParams">
                    <div>
                        <!-- <span class="reset_btn"></span> -->
                        重置
                    </div>
                </el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card class="!border-none" shadow="never">
        <el-space>
            <el-button type="primary" @click="addUser"> 添加教师 </el-button>

            <el-upload
                ref="upload"
                class="upload-demo"
                :action="`${config.baseUrl}${config.urlPrefix}/school.teacher/importTeacher`"
                :limit="1"
                :headers="{
                    token: `${userStore.token}`
                }"
                :show-file-list="false"
                :on-success="uploadSuccess"
            >
                <el-button>批量导入</el-button>
            </el-upload>

            <el-button>
                <a
                    :href="`${config.baseUrl}/uploads/file/20250122/202501222152111b8120721.xlsx`"
                    target="_blank"
                    rel="noopener noreferrer"
                >
                    下载模板
                </a></el-button
            >
        </el-space>

        <el-table
            stripe
            class="mt-2"
            size="large"
            v-loading="pager.loading"
            :data="pager.lists"
            @selection-change="handleSelectionChange"
        >
            <!-- <el-table-column type="selection" width="55"></el-table-column> -->
            <el-table-column label="教师ID" prop="id" min-width="120"></el-table-column>
            <el-table-column label="教师名称" prop="real_name" min-width="100"></el-table-column>
            <el-table-column label="所属院系" prop="classes" min-width="120">
                <template #default="{ row }">
                    <el-space wrap>
                        <el-tag type="primary" size="mini">{{
                            row.classes?.[0]?.college?.name
                        }}</el-tag>
                    </el-space>
                </template>
            </el-table-column>
            <el-table-column label="所属班级" prop="classesname" min-width="300">
                <template #default="{ row }">
                    <el-space wrap>
                        <el-tag
                            v-for="(item, index) in row.classes"
                            :key="index"
                            type="primary"
                            size="mini"
                            >{{ item?.name }}</el-tag
                        >
                    </el-space>
                </template>
            </el-table-column>
            <el-table-column label="班级学生（人）" prop="classes" min-width="140">
                <template #default="{ row }">
                    {{ studentNum(row.classes) }}
                </template>
            </el-table-column>
            <el-table-column label="学生作品（个）" prop="inviter_name" min-width="140">
                <template #default="{ row }">
                    {{ workNum(row.classes) }}
                </template>
            </el-table-column>
            <el-table-column label="账号状态" min-width="160">
                <template #default="{ row }">
                    <span style="color: #1abc9c" v-if="row.status == 1">• 启用</span>
                    <span style="color: #f59a23" v-else>• 停用</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="created_at" min-width="180"></el-table-column>

            <el-table-column label="操作" min-width="200" fixed="right">
                <template #default="{ row }">
                    <div class="flex items-center">
                        <el-button link type="primary" @click="gotoDeatil(row)"> 查看 </el-button>
                        <el-button link type="primary" @click="handleEdit(row)"> 编辑 </el-button>
                        <el-button
                            type="warning"
                            link
                            v-if="row.status == 1"
                            @click="BlackList(row)"
                        >
                            停止
                        </el-button>
                        <el-button
                            type="success"
                            link
                            v-if="row.status == 2"
                            @click="BlackList(row)"
                        >
                            启用
                        </el-button>
                        <el-button type="danger" link plain @click="handleDelete(row)">
                            删除
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div class="flex justify-end mt-4">
            <pagination
                v-model="pager"
                @change="getLists"
                background="red"
                layout="prev, pager, next, sizes"
            ></pagination>
        </div>
    </el-card>

    <add-user-pop
        v-if="popShow"
        ref="addUserPopRef"
        @close="popClose"
        @submit="popConfirm"
    ></add-user-pop>
</template>
<script lang="ts" setup name="consumerLists">
import { usePaging } from '@/hooks/usePaging'
import { getTeacherList, editTeacher, delTeacher, getDepartmentList } from '@/api/consumer'
import feedback from '@/utils/feedback'
import addUserPop from './modals/addUserPop.vue'
import { useRequest } from 'vue-hooks-plus'
import config from '@/config'
import useUserStore from '@/stores/modules/user'
import { ElMessage } from 'element-plus'
const userStore = useUserStore()

const router = useRouter()

// 获取学院配置
const { data } = useRequest(async () => {
    const _Res = await getDepartmentList({
        page_no: 1, page_size: 9999 
    })

    const list: any = []

    _Res?.lists?.forEach((_item) => {
        if (_item?.classes && _item?.classes?.length > 0) {
            list.push({
                value: _item.id,
                label: _item.name,
                children: _item?.classes?.map((_item2) => {
                    return {
                        value: _item2.id,
                        label: _item2.name
                    }
                })
            })
        }
    })

    return list
})

//弹框ref
const addUserPopRef = shallowRef()
const popShow = ref(false)

const queryParams = reactive({
    real_name: '',
    created_start_date: '',
    created_end_date: '',
    college_id: '',
    classes_id: '',
    value2: '',
    college: ''
})

const collegeChange = (_data) => {
    queryParams.college_id = _data?.[0]
    queryParams.classes_id = _data?.[1]
}

const dateChange = (_data) => {
    queryParams.created_start_date = _data?.[0]
    queryParams.created_end_date = _data?.[1]
}

const isSelect = ref<number[]>([])

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: getTeacherList,
    params: queryParams
})

// 计算学生人数
const studentNum = (_item) => {
    return _item.reduce((acc, cur) => acc + cur.student_num, 0)
}

// 计算作品数
const workNum = (_item) => {
    return _item.reduce((acc, cur) => acc + cur.works_num, 0)
}

//打开创建用户弹框
const addUser = async () => {
    popShow.value = true
    await nextTick()
    addUserPopRef.value.open()
    //   addUserPopRef.value.setFormData({
    //     nickname: "测试",
    //   });
}

//删除
const handleDelete = async (data: any) => {
    await feedback.prompt(`是否确定删除该教师？`, `操作确认`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea',
        inputPlaceholder: '请输入备注',
        callback: async ({ action, value }: any) => {
            if (action == 'confirm') {
                console.log('确认了')
                try {
                    await delTeacher({ id: data?.id, remark: value })

                    getLists()
                } catch (error) {}
            } else {
            }
        },
        type: 'warning'
    })
}

//黑名单
const BlackList = async (data) => {
    await feedback.prompt(
        `是否确定${data?.status == 1 ? '停用' : '启用'}该教师账号？`,
        `操作确认`,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputType: 'textarea',
            inputPlaceholder: '请输入备注',
            callback: async ({ action, value }: any) => {
                if (action == 'confirm') {
                    console.log('确认了')
                    try {
                        await editTeacher({
                            ...data,
                            id: data.id,
                            classes_ids: data.classes?.map((e) => e.id)?.join(','),
                            status: data.status === 1 ? 2 : 1,
                            remark: value
                        })

                        getLists()
                    } catch (error) {}
                } else {
                }
            },
            type: 'warning'
        }
    )
}

//多选
const handleSelectionChange = (value: any) => {
    isSelect.value = value.map((item: any) => item.id)
}

//弹框关闭
const popClose = () => {
    popShow.value = false
}

const popConfirm = () => {
    getLists()
    popShow.value = false
}

onActivated(() => {
    getLists()
})

getLists()

// 路由跳转
const gotoDeatil = (data: any) => {
    router.push(`/user/teacher/detail?id=${data?.id}`)
}

// 编辑
const handleEdit = async (data: any) => {
    popShow.value = true
    await nextTick()
    addUserPopRef.value.open()

    const _classes_ids = data.classes.map((item: any) => {
        return [item?.college_id, item?.id]
    })

    addUserPopRef.value.setFormData({
        ...data,
        password_confirm: data.password,
        status: data?.status === 1,
        classes_ids: _classes_ids
    })
}

const uploadSuccess = () => {
    ElMessage({
        message: '批量导入成功',
        type: 'success'
    })
    getLists()
}
</script>

<style lang="scss" scoped></style>
